package com.zhongyouyun.admin.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhongyouyun.admin.model.*;
import com.zhongyouyun.admin.pojo.UserDetailPojo;
import com.zhongyouyun.admin.pojo.UserPojo;
import com.zhongyouyun.admin.service.RoleMenuService;
import com.zhongyouyun.admin.vo.UserVo;
import com.zhongyouyun.other.annotation.DataAuthScope;
import com.zhongyouyun.other.annotation.XianMuAuthScope;
import com.zhongyouyun.other.model.PageRequest;
import com.zhongyouyun.other.model.Result;
import com.zhongyouyun.utils.ModelUtils;
import com.zhongyouyun.utils.QueryUtils;
import io.swagger.annotations.*;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zhongyouyun.admin.service.UserService;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: shenyi
 * @Date: 2021-09-23
 * @Description: 用户表
 */
@RestController
@RequestMapping("/admin/z_user")
@Api(value = "用户信息controller", tags = {"用户信息操作接口"})
public class UserController {
    @Autowired
    private UserService service;
    @Autowired
    private RoleMenuService roleMenuService;

    @PostMapping("/findPage")
    @ResponseBody
    @ApiOperation(value = "获取用户信息", notes = "通过用户姓名获取用户信息")
    @DataAuthScope(deptAlias = "temp_data_scope.")
    @XianMuAuthScope(deptAlias = "temp_data_scope.")
    public IPage<UserPojo> findPage(@RequestBody PageRequest pageRequest) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        QueryUtils.fiterQuery(queryWrapper, pageRequest);
        Page page = new Page(pageRequest.getPageNum(), pageRequest.getPageSize());
        return service.selectPojoPage(page, queryWrapper);
    }

    @GetMapping("/findRoleMenuTree")
    @ResponseBody
    @ApiOperation(value = "获取用户角色菜单", notes = "通过用户信息获取用户角色权限")
    @XianMuAuthScope(deptAlias = "temp_data_scope.")
    public Result<List<MenuModel>> findRoleMenuTree(@ApiParam(name = "用户ID", value = "id", required = true) @RequestParam(value = "id") String id) {
        List<MenuModel> list = roleMenuService.findPermissions(id);
        if (list.size() > 0) {
            return Result.<List<MenuModel>>builder().message("成功").status(0).data(list).build();
        } else {
            return Result.<List<MenuModel>>builder().success(true).status(1).build();
        }
    }

    @GetMapping("/getDetails")
    @ResponseBody
    @ApiOperation(value = "获取用户详情", notes = "获取用户详情")
    public Result getDetails(@ApiParam(name = "用户ID", value = "id", required = true) @RequestParam(value = "id") String id) {
        UserDetailPojo userDetailPojo = service.getDetails(Long.valueOf(id));
        if (ObjectUtil.isNotEmpty(userDetailPojo)) {
            return Result.builder().message("成功").status(0).data(userDetailPojo).build();
        } else {
            return Result.builder().message("获取失败").success(false).status(1).build();
        }
    }

    @PostMapping("/upState")
    @ResponseBody
    @ApiOperation(value = "修改用户停用状态", notes = "通过用户ID修改用户状态")
    public Result upState(@RequestBody UserVo userVo) {

        UserModel userModel = service.getById(userVo.getUserId());
        userModel.setState(userVo.getState());
        Boolean flag = service.updateById(userModel);
        if (flag) {
            return Result.builder().message("成功").status(0).build();
        } else {
            return Result.builder().message("修改失败").success(false).status(1).build();
        }


    }


    @PostMapping("/saveOrUpate")
    @ResponseBody
    @ApiOperation(value = "修改或者新增", notes = "通过ID判断修改或者新增")
    public Result saveOrUpate(@RequestBody UserModel userModel, HttpServletRequest request) {
        String type= request.getHeader("xiangmuType");
        userModel.setXiangMuType(type);
        UserModel model = (UserModel) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
        if (ObjectUtil.isNotEmpty(model.getId()) && ObjectUtil.isNotEmpty(userModel.getId())) {
            userModel.setUpdateBy(model.getId().toString());
            UserModel u = service.getById(model.getId());

        } else {
            ModelUtils modelutils = new ModelUtils();
            modelutils.initModel(userModel, model.getId().toString());
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_name", userModel.getUserName());
            UserModel user = service.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(user)) {
                return Result.builder().message("用户已存在").success(false).status(1).build();
            }
        }

        Boolean flag = service.saveUser(userModel,type);
        if (flag) {
            return Result.builder().message("成功").status(0).build();
        } else {
            return Result.builder().message("保存失败").success(false).status(1).build();
        }
    }

    @GetMapping("/delete")
    @ResponseBody
    @ApiOperation(value = "删除", notes = "通过ID删除")
    public Result delete(@ApiParam(name = "用户ID", value = "id", required = true) @RequestParam(value = "id") String id) {
        Boolean flag = false;
        flag = service.removeById(Long.valueOf(id));
        if (flag) {
            return Result.builder().message("成功").status(0).build();
        } else {
            return Result.builder().message("删除失败").success(false).status(1).build();
        }
    }

    @PostMapping("/batchDelete")
    @ResponseBody
    @ApiOperation(value = "删除", notes = "通过ID删除")
    public Result batchDelete(@RequestBody List<String> ids) {
        List<Long> list = new ArrayList<Long>();
        ids.forEach(id -> {
            list.add(Long.valueOf(id));
        });
        Boolean flag = service.removeByIds(list);
        if (flag) {
            return Result.builder().message("成功").status(0).build();
        } else {
            return Result.builder().message("删除失败").success(false).status(1).build();
        }
    }

}
